import { Request, Response } from "express";
import { User } from "../db";
import { Token } from "../token";
import { create } from "./event-type";
import { IAuthorization, waitTime, checkAuthorization } from "./util";

async function getFakeCaptcha(req: Request, res: Response) {
  await waitTime(2000);
  return res.json("captcha-xxx");
}

export default {
  "GET /api/currentUser": async (req: Request, res: Response) => {
    const Authorization = req.get("Authorization") as string;
    if (checkAuthorization(req, res)) return;
    const resDecode = Token.decodeToken<IAuthorization>(Authorization);
    if (!resDecode) {
      res.send({
        success: false,
        data: null,
        errorCode: "700",
        errorMessage: "令牌过期",
      });
      return;
    }
    const { payload } = resDecode;

    const currentUser = await User.findOne({
      where: { id: payload.data.userId },
    });
    if (!currentUser) {
      res.send({
        success: false,
        data: null,
        errorCode: "701",
        errorMessage: "该用户不存在！",
      });
      return;
    }
    res.send({
      success: true,
      data: currentUser,
    });
  },
  "GET /api/users": async (req: Request, res: Response) => {
    if (checkAuthorization(req, res)) return;
    const { current, pageSize } = req.query as any;
    const total = await User.count();
    const rows = await User.findAll({
      attributes: [
        "id",
        "name",
        "nickname",
        "email",
        "phone",
        "createdAt",
        "updatedAt",
      ],
      offset: parseInt(`${(current - 1) * pageSize}`) || 0,
      limit: parseInt(pageSize) || 20,
      order: [["createdAt", "DESC"]],
    });
    res.send({
      success: true,
      total,
      data: rows,
    });
  },
  "POST /api/login/account": async (req: Request, res: Response) => {
    const { password, username } = req.body;
    const currentUser = await User.findOne({ where: { name: username } });
    if (!currentUser) {
      res.send({
        success: false,
        data: null,
        errorCode: "701",
        errorMessage: "该用户不存在！",
      });
      return;
    }

    if (currentUser.get("password") !== password) {
      res.send({
        success: false,
        data: null,
        errorCode: "702",
        errorMessage: "密码输入不正确！",
      });
      return;
    }

    res.send({
      success: true,
      data: {
        currentAuthority: currentUser.get("access"),
        accessToken: Token.createToken<IAuthorization>({
          userId: currentUser.get("id") as string,
        }),
      },
    });
  },
  "POST /api/login/register": async (req: Request, res: Response) => {
    const { password, username } = req.body;
    const currentUser = await User.create({
      password,
      nickname: username,
      name: username,
    });
    const userId = currentUser.get("id") as string;
    await create(userId);

    res.send({
      success: true,
      data: {
        currentAuthority: currentUser.get("access"),
        accessToken: Token.createToken<IAuthorization>({ userId }),
      },
    });
  },
  "POST /api/updateToken": async (req: Request, res: Response) => {
    const Authorization = req.get("Authorization") as string;
    const result = Token.decodeToken(Authorization);
    if (!result) {
      res.send({
        success: false,
        data: null,
        errorCode: "703",
        errorMessage: "令牌不合法",
      });
      return;
    }
    const userId = result.payload.data.userId as string;
    res.send({
      success: true,
      data: {
        accessToken: Token.createToken<IAuthorization>({ userId }),
      },
    });
  },
  "POST /api/login/outLogin": (req: Request, res: Response) => {
    if (checkAuthorization(req, res)) return;
    res.send({ data: {}, success: true });
  },
  "GET /api/500": (req: Request, res: Response) => {
    res.status(500).send({
      timestamp: 1513932555104,
      status: 500,
      error: "error",
      message: "error",
      path: "/base/category/list",
    });
  },
  "GET /api/404": (req: Request, res: Response) => {
    res.status(404).send({
      timestamp: 1513932643431,
      status: 404,
      error: "Not Found",
      message: "No message available",
      path: "/base/category/list/2121212",
    });
  },
  "GET /api/403": (req: Request, res: Response) => {
    res.status(403).send({
      timestamp: 1513932555104,
      status: 403,
      error: "Forbidden",
      message: "Forbidden",
      path: "/base/category/list",
    });
  },
  "GET /api/401": (req: Request, res: Response) => {
    res.status(401).send({
      timestamp: 1513932555104,
      status: 401,
      error: "Unauthorized",
      message: "Unauthorized",
      path: "/base/category/list",
    });
  },
  "GET /api/login/captcha": getFakeCaptcha,
};
